// 引入VueRouter
import { createRouter, createWebHistory} from 'vue-router'
import { ElMessage } from 'element-plus'

// 定义路由规则
const routes = [
    // 访问路径为/默认跳转路径为/home
    {
        path: '/',
        redirect: '/home'
    },
    {
        name: 'login',
        path: '/login',
        meta: {
            title: '登录'
        },
        component: () => import('@/views/login/index.vue')
    },
    {
        name: 'home',
        path: '/home',
        redirect: '/home/home',
        meta: {
            title: '首页'
        },
        component: () => import('@/views/home/index.vue'),
        children: [
            {
                path: 'home',
                component: () => import('@/views/system/home/index.vue')
            },
            {
                path: 'user',
                component: () => import('@/views/system/user/index.vue')
            },
            {
                path: 'goods',
                component: () => import('@/views/shopping/goods/index.vue')
            },
            {
                path: 'order',
                component: () => import('@/views/shopping/order/index.vue')
            }
        ]
    },
]

// 配置路由
const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_APP_BASE_PATH),
  routes
})

router.beforeEach((to, from, next) => {
    // 1. 获取登陆令牌
    const authorization = sessionStorage.getItem('authorization')
    // 2. 判断是否前往登录页
    if (authorization && to.name === 'login') {
        next('/')
    }
    if (!authorization && to.name !== 'login') {
        ElMessage.warning('请登陆后再进行访问')
        next('/login')
    }
    next()
})

// 导出路由
export default router